﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
namespace ComputerVision.Common
{
    public class Utilities
    {
        public static bool IsFormOpen(Form form)
        {
            foreach (Form f in Application.OpenForms)
                if (f.Name.Equals(form.Name) && f.Text.Equals(form.Text))
                    return true;
            return false;
        }

        public static bool IsFormOpen(string formName)
        {
            foreach (Form f in Application.OpenForms)
                if (f.Name.Equals(formName))
                    return true;
            return false;
        }

        public static void ActiveForm(Form form)
        {
            foreach (Form f in Application.OpenForms)
                if (f.Name.Equals(form.Name) && f.Text.Equals(form.Text))
                {
                    f.Activate();
                    break;
                }
            form.Dispose();
        }

        public static void CloseOldForm(Form form)
        {
            foreach (Form f in Application.OpenForms)
                if (f.Name.Equals(form.Name) && f.Text.Equals(form.Text))
                {
                    f.Close();
                    break;
                }
        }

        public static void CloseOldFormByName(string formName)
        {
            foreach (Form f in Application.OpenForms)
                if (f.Name.Equals(formName))
                {
                    f.Close();
                    
                    //break;
                }
            System.GC.Collect();
        }

        public static void CloseAllOldForm()
        {
            int countF = Application.OpenForms.Count;
            Form form;

            for (int i = 0; i < countF; i++)
            {
                form = Application.OpenForms[i];

                if (!form.Name.Equals("frmMain") && !form.Name.Equals("frmLogin"))
                {
                    form.Close();
                    countF--;
                    //break;
                }
            }

            //foreach (Form f in Application.OpenForms)
            //    if (!f.Name.Equals("frmMain"))
            //    {
            //        f.Close();
                    
            //        //break;
            //    }
            //System.GC.Collect();
        }

        public static byte[] DecryptData(byte[] data, string password, PaddingMode paddingMode)
        {
            if (data == null || data.Length == 0)
                throw new ArgumentNullException("data");
            if (password == null)
                throw new ArgumentNullException("password");
            PasswordDeriveBytes passwordDeriveBytes = new PasswordDeriveBytes(password, Encoding.UTF8.GetBytes("Salt"));
            RijndaelManaged rijndaelManaged = new RijndaelManaged();
            rijndaelManaged.Padding = paddingMode;
            ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(passwordDeriveBytes.GetBytes(16), passwordDeriveBytes.GetBytes(16));
            using (MemoryStream memoryStream = new MemoryStream(data))
            {
                using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))
                {
                    byte[] buffer = new byte[data.Length];
                    int count = cryptoStream.Read(buffer, 0, buffer.Length);
                    if (count >= buffer.Length)
                        return buffer;
                    byte[] numArray = new byte[count];
                    Buffer.BlockCopy((Array)buffer, 0, (Array)numArray, 0, count);
                    return numArray;
                }
            }
        }

        public static string DecryptData(string data, string password)
        {
            if (data == null)
                throw new ArgumentNullException("data");
            if (password == null)
                throw new ArgumentNullException("password");
            else
                return Encoding.UTF8.GetString(Utilities.DecryptData(Convert.FromBase64String(data), password, PaddingMode.ISO10126));
        }

        public static string Dec(string s)
        {
            return Utilities.DecryptData(s, Encoding.UTF8.GetString(Convert.FromBase64String("YmYwYjA5N2YtZTI3MC00M2NmLWE5M2ItMjNlYzE1MDlmNjYy")));
        }

        public static void ExportToExcel(GridView gridView, int type, bool openNow)
        {
            if (gridView == null) return;

            //First: Change gridView's property PrintSelectedRowOnly to True
            gridView.OptionsPrint.PrintSelectedRowsOnly = true;
            gridView.OptionsSelection.MultiSelect = true;
            switch (type)
            {
                //0: Export selected rows
                case 0:
                    if (gridView.RowCount > 0)
                    {
                        try
                        {
                            bool success = false;
                            XlsxExportOptions option = new XlsxExportOptions();
                            option.ShowGridLines = true;
                            option.SheetName = gridView.ViewCaption;
                            //option.TextExportMode = te

                            FileDialog fileDialog = new SaveFileDialog();
                            fileDialog.Filter = @"Excel 2007-2013|*.xlsx|Excel 97-2003 (*.xls)|*.xls";
                            fileDialog.FileName = gridView.ViewCaption;
                            if (fileDialog.ShowDialog() == DialogResult.OK)
                            {
                                //gridView.BeginUpdate();
                                //gridView.BestFitColumns();
                                //gridView.Columns[1].Visible = false;
                                //gridView.Columns[2].Visible = false;
                                //gridView.Columns[3].Visible = false;
                                gridView.ExportToXlsx(fileDialog.FileName, option);
                                //gridView.Columns[1].Visible = true;
                                //gridView.Columns[2].Visible = true;
                                //gridView.Columns[3].Visible = true;
                                //gridView.EndUpdate();
                                success = true;

                            }

                            if (success && openNow && MessageBox.Show("Bạn có muốn mở file này?", "Message", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                System.Diagnostics.Process process = new System.Diagnostics.Process();
                                process.StartInfo.FileName = fileDialog.FileName;
                                process.StartInfo.Verb = "Open";
                                process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                                process.Start();

                            }

                        }
                        catch (Exception ex)
                        {

                            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                    }
                    else
                    {
                        MessageBox.Show("No data to export.", "Message",
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    break;

                //1: Export all
                case 1:
                    if (gridView.RowCount > 0)
                    {
                        try
                        {
                            bool success = false;
                            XlsxExportOptions option = new XlsxExportOptions();
                            option.ShowGridLines = true;
                            option.SheetName = gridView.ViewCaption;

                            FileDialog fileDialog = new SaveFileDialog();
                            fileDialog.Filter = @"Excel 2007-2013|*.xlsx|Excel 97-2003 (*.xls)|*.xls";
                            fileDialog.FileName = @"Data";
                            if (fileDialog.ShowDialog() == DialogResult.OK)
                            {
                                //gridView.BestFitColumns();
                                gridView.SelectAll();
                                gridView.ExportToXlsx(fileDialog.FileName, option);
                                success = true;
                            }

                            if (success && openNow && MessageBox.Show("Bạn có muốn mở file này?", "Message", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                System.Diagnostics.Process process = new System.Diagnostics.Process();
                                process.StartInfo.FileName = fileDialog.FileName;
                                process.StartInfo.Verb = "Open";
                                process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                                process.Start();

                            }
                        }
                        catch (Exception ex)
                        {

                            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                    }
                    else
                    {
                        MessageBox.Show("No data to export.", "Message",
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    break;

                default:
                    break;
            }

        }
    }
}